﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iLangl.Model;
using iLangl.BusinessModel.DAL;

namespace iLangl.BusinessModel.Managers
{
	public class WorkAreaManager
	{
		#region Singelton Pattern
		private WorkAreaManager()
		{
		}

		private static WorkAreaManager instance;
		private static object mutex = new object();
		/// <summary>
		/// The instance of the WokrAreaManager.
		/// </summary>
		public static WorkAreaManager Instance
		{
			get
			{
				if (instance == null)
				{
					lock (mutex)
					{
						if (instance == null)
						{
							instance = new WorkAreaManager();
						}
					}
				}
				return instance;
			}
		}
		#endregion

		public IList<WorkArea> GetWorkAres()
		{
			return DALFacade.Instance.WorkAreaDAL.ReadWorkAreas();
		}

		public WorkArea GetTPWorkArea(String providerId, String workAreaId)
		{
			return DALFacade.Instance.WorkAreaDAL.ReadTpWorkArea(providerId, workAreaId);
		}

		public void RegisterTPWorkAreas(IList<TPWorkArea> workAreaList)
		{
			foreach (TPWorkArea tpworkArea in workAreaList)
			{
				RegisterTPWorkArea(tpworkArea);
			}
		}

		public void RegisterTPWorkArea(TPWorkArea tpworkarea)
		{
			WorkArea workarea = DALFacade.Instance.WorkAreaDAL.ReadWorkAreaById(tpworkarea.Id);

			if (workarea == null)
			{
				workarea = DALFacade.Instance.WorkAreaDAL.ReadWorkAreaByName(tpworkarea.Name);
				tpworkarea.IsApproved = false;
			}

			//If area didn't exists we create a new one
			if (workarea == null)
			{
				workarea = new WorkArea();
				workarea.Id = tpworkarea.Id;
				workarea.Name = tpworkarea.TPWorkAreaName;
				workarea.ParentId = tpworkarea.ParentId;
				workarea.IsApproved = false;

				DALFacade.Instance.WorkAreaDAL.AddWorkArea(workarea, null);
			}

			tpworkarea.Id = workarea.Id;
			tpworkarea.Name = workarea.Name;
			tpworkarea.ParentId = workarea.ParentId;

			DALFacade.Instance.WorkAreaDAL.AddTPWorkArea(tpworkarea, null);
		}
	}
}
